import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { renderWithAppContext } from '../../__helpers__/test-utils';
import { mockSettings } from '../../__mocks__/state-mocks';
import { GroupBy } from '../../types';
import { mockSingleNotification } from '../../utils/api/__mocks__/response-mocks';
import * as comms from '../../utils/comms';
import { NotificationHeader } from './NotificationHeader';

describe('renderer/components/notifications/NotificationHeader.tsx', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should render itself & its children - group by repositories', async () => {
    const props = {
      notification: mockSingleNotification,
    };

    const tree = renderWithAppContext(<NotificationHeader {...props} />, {
      settings: { ...mockSettings, groupBy: GroupBy.REPOSITORY },
    });

    expect(tree).toMatchSnapshot();
  });

  describe('should render itself & its children - group by date', () => {
    it('with notification number', async () => {
      const props = {
        notification: mockSingleNotification,
      };

      const tree = renderWithAppContext(<NotificationHeader {...props} />, {
        settings: { ...mockSettings, groupBy: GroupBy.DATE },
      });

      expect(tree).toMatchSnapshot();
    });

    it('with showNumber setting disabled', async () => {
      const props = {
        notification: mockSingleNotification,
      };

      const tree = renderWithAppContext(<NotificationHeader {...props} />, {
        settings: {
          ...mockSettings,
          showNumber: false,
          groupBy: GroupBy.DATE,
        },
      });

      expect(tree).toMatchSnapshot();
    });

    it('without notification number', async () => {
      const props = {
        notification: {
          ...mockSingleNotification,
          subject: { ...mockSingleNotification.subject, number: null },
        },
      };

      const tree = renderWithAppContext(<NotificationHeader {...props} />, {
        settings: { ...mockSettings, groupBy: GroupBy.DATE },
      });

      expect(tree).toMatchSnapshot();
    });
  });

  it('should open notification user profile - group by date', async () => {
    const openExternalLinkSpy = jest
      .spyOn(comms, 'openExternalLink')
      .mockImplementation();

    const props = {
      notification: mockSingleNotification,
    };

    renderWithAppContext(<NotificationHeader {...props} />, {
      settings: { ...mockSettings, groupBy: GroupBy.DATE },
    });

    await userEvent.click(screen.getByTestId('view-repository'));

    expect(openExternalLinkSpy).toHaveBeenCalledTimes(1);
    expect(openExternalLinkSpy).toHaveBeenCalledWith(
      props.notification.repository.html_url,
    );
  });
});
